package com.cms.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

/**
 * Utils - HttpClient
 * 
 * 
 * 
 */
public class HttpClientUtil{

	
	/**
	 * POST请求
	 * 
	 * @param url
	 *            URL
	 * @param file
	 *            请求参数
	 * @return 返回结果
	 */
	public static String post(String url, File file) {
		String result = null;
		CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
		try {
			HttpPost httpPost = new HttpPost(url);
			FileBody fileBody = new FileBody(file);
			MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			multipartEntity.addPart("media", fileBody);
			httpPost.setEntity(multipartEntity);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity,"UTF-8");
			EntityUtils.consume(httpEntity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}
	
	
	/**
	 * POST请求
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 */
	public static String post(String url, Map<String, Object> parameterMap,Map<String, String> headerMap) {
	    System.out.println(url);
	    System.out.println(parameterMap);
		String result = null;
		CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
		try {
			HttpPost httpPost = new HttpPost(url);
			if(headerMap!=null){
				for (Entry<String, String> entry : headerMap.entrySet()) {
					httpPost.setHeader(entry.getKey(), entry.getValue());
				}
			}
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (parameterMap != null) {
				for (Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity,"UTF-8");
			EntityUtils.consume(httpEntity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}
	
	/**
	 * POST请求
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 */
	public static String post(String url, String postBody) {
		String result = null;
		CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity entity = new StringEntity(postBody,"UTF-8");
			httpPost.setEntity(entity);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity,"UTF-8");
			EntityUtils.consume(httpEntity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}
	
	/**
	 * POST请求
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 */
	public static String postt(String url, String postBody) {
		String result = null;
		CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity entity = new StringEntity(postBody,"UTF-8");
			entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");  
			httpPost.setEntity(entity);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity,"UTF-8");
			EntityUtils.consume(httpEntity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}


	/**
	 * GET请求
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 */
	public static String get(String url, Map<String, Object> parameterMap) {
	    System.out.println("===URL=="+url);
	    System.out.println("===parameterMap=="+parameterMap);
		String result = null;
		CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (parameterMap != null) {
				for (Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity,"UTF-8");
			EntityUtils.consume(httpEntity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}
	   
    public static String submitFilePost(String url,String filename1,String filename2, String filepath){  
    	 HttpClient httpclient = HttpClientBuilder.create().build();
    	 String result = null;
        try {  
      
            HttpPost httppost = new HttpPost(url);  
            HttpEntity httpEntity = MultipartEntityBuilder.create().addTextBody("filename1", filename1)
            .addBinaryBody("file1", new File(filepath + File.separator + filename1))
            .addBinaryBody("file2", new File(filepath + File.separator + filename2))
            .build();
            httppost.setEntity(httpEntity);  
              
            HttpResponse response = httpclient.execute(httppost);  
              
                  
            int statusCode = response.getStatusLine().getStatusCode();  
              
                  
            if(statusCode == HttpStatus.SC_OK){  
                      
                System.out.println("服务器正常响应.....");  
                  
                HttpEntity resEntity = response.getEntity();  
                result = EntityUtils.toString(resEntity);
                EntityUtils.consume(resEntity);  
            }  
                  
            } catch (ParseException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }
 
        return result;
        } 
    public static String submitInputStreamPost(String url,InputStream inputS,String fileName){  
    	HttpClient httpclient = HttpClientBuilder.create().build();
    	String result = null;
    	try {  
    		
    		HttpPost httppost = new HttpPost(url);  
    		ContentBody cb = new InputStreamBody(inputS, fileName);
    		FormBodyPart bodyPart = FormBodyPartBuilder.create().setName("file").setBody(cb).build();
    		HttpEntity httpEntity = MultipartEntityBuilder.create()
    				.addPart(bodyPart).setLaxMode()
    				.build();
    		httppost.setEntity(httpEntity);  
    		
    		HttpResponse response = httpclient.execute(httppost);  
    		
    		
    		int statusCode = response.getStatusLine().getStatusCode();  
    		
    		
    		if(statusCode == HttpStatus.SC_OK){  
    			
    			System.out.println("服务器正常响应.....");  
    			
    			HttpEntity resEntity = response.getEntity();  
    			result = EntityUtils.toString(resEntity);
    			EntityUtils.consume(resEntity);  
    		}  
    		
    	} catch (ParseException e) {  
    		e.printStackTrace();  
    	} catch (IOException e) {  
    		e.printStackTrace();  
    	}
    	
    	return result;
    } 
    public static void downloadFile(String url,String filePath){  
    	try {  
    		HttpClient httpclient = HttpClientBuilder.create().build();
    		HttpGet httppost = new HttpGet(url);  
    		HttpResponse response = httpclient.execute(httppost);  
    		int statusCode = response.getStatusLine().getStatusCode();  
    		System.out.println(statusCode);
    		
    		if(statusCode == HttpStatus.SC_OK){  
    			
    			System.out.println("服务器正常响应.....");  
    			
    			HttpEntity resEntity = response.getEntity();  
    			InputStream in = resEntity.getContent();
    			FileOutputStream fos = new FileOutputStream(new File(filePath));
    			IOUtils.copy(in, fos);
    			EntityUtils.consume(resEntity);  
    		}  
    		
    	} catch (Exception e) {  
    		e.printStackTrace();  
    	} 
    	
    } 
    public static InputStream downloadFile(String url){  
    	HttpClient httpclient = HttpClientBuilder.create().build();
    	String result = null;
    	try {  
    		
    		HttpGet httppost = new HttpGet(url);  
    		
    		HttpResponse response = httpclient.execute(httppost);  
    		
    		
    		int statusCode = response.getStatusLine().getStatusCode();  
    		System.out.println(statusCode);
    		
    		if(statusCode == HttpStatus.SC_OK){  
    			
    			System.out.println("服务器正常响应.....");  
    			
    			HttpEntity resEntity = response.getEntity();  
    			InputStream in = resEntity.getContent();
    			return in;  
    		}  
    		
    	} catch (ParseException e) {  
    		e.printStackTrace();  
    	} catch (IOException e) {  
    		e.printStackTrace();  
    	}
    	return null;
    } 
    
    
	   public static CloseableHttpClient createSSLClientDefault(){
	        try {
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    //信任所有
                    public boolean isTrusted(X509Certificate[] chain,
                                    String authType) throws CertificateException {
                        return true;
                    }
                }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
                return HttpClients.custom().setSSLSocketFactory(sslsf).build();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyStoreException e) {
                e.printStackTrace();
            }
            return  HttpClients.createDefault();
       }
    public static void main(String[] args) throws FileNotFoundException {
////    	downloadFile("http://10.19.10.214:8081/other/materials//2017/04/01/d3cef1b4e3e7481fbbcea80324407973.jpg"	,"d://data/robotImages/test/", "我的.jpg");
//    	InputStream in = downloadFile("http://10.19.10.214:8081/other/materials//2017/04/01/d3cef1b4e3e7481fbbcea80324407973.jpg"	 );
//    	InputStream in2 = downloadFile("http://10.19.10.214:8081/other/materials//2017/04/01/d3cef1b4e3e7481fbbcea80324407973.jpg"	 );
////    	InputStream in  = new FileInputStream(new File("D:/data/robotImages/2016-10-15/1cb3a66c-48c1-4f6a-8ac8-7ad053dbef54.jpg"));
////    	InputStream in2 = new FileInputStream(new File("D:/data/robotImages/2016-10-15/3d1c3ab0-af76-4ce4-bcac-6a12c13f463e.jpg"));
//        ZipFile zipFile;
//        try {
//            zipFile = new ZipFile(new File("d://data/robotImages/test/我的1.zip"));
//            ZipParameters parameters = new ZipParameters();
//            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
//            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
//            parameters.setFileNameInZip("teset1.jpg");
//            parameters.setSourceExternalStream(true);
//            zipFile.addStream(in, parameters);
//            ZipParameters parameters2 = new ZipParameters();
//            parameters2.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
//            parameters2.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
//            parameters2.setFileNameInZip("teset2.jpg");
//            parameters2.setSourceExternalStream(true);
//            zipFile.addStream(in2, parameters2);
//        } catch (ZipException e) {
//            e.printStackTrace();
//        }
    	
    	System.out.println(get("https://www.saiwuquan.com", null));
	}
}
